package com.dy.yunying.biz.service.prize.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.constant.Constant;
import com.dy.yunying.api.entity.ParentGameArea;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.entity.hongbao.*;
import com.dy.yunying.api.entity.prize.*;
import com.dy.yunying.api.entity.usergroup.UserGroup;
import com.dy.yunying.api.enums.*;
import com.dy.yunying.api.req.prize.PrizeConfigReq;
import com.dy.yunying.api.req.prize.PrizeOnlineOrOfflineReq;
import com.dy.yunying.api.req.prize.PrizePushReq;
import com.dy.yunying.api.req.sign.CommonNoticeReq;
import com.dy.yunying.api.resp.hongbao.CommonNoticeVo;
import com.dy.yunying.api.resp.hongbao.NodeData;
import com.dy.yunying.api.resp.hongbao.NodeParentData;
import com.dy.yunying.api.resp.prize.PrizeConfigRes;
import com.dy.yunying.api.resp.prize.PrizePushRes;
import com.dy.yunying.api.vo.usergroup.UserGroupStatVO;
import com.dy.yunying.biz.dao.ads.hongbao.HbActivityMapper;
import com.dy.yunying.biz.dao.ads.hongbao.HbSdkDynamicMenusMapper;
import com.dy.yunying.biz.dao.ads.prize.*;
import com.dy.yunying.biz.dao.manage.ParentGameAreaMapper;
import com.dy.yunying.biz.dao.manage.ext.GameDOMapperExt;
import com.dy.yunying.biz.dao.manage.ext.ParentGameDOMapperExt;
import com.dy.yunying.biz.dao.manage.ext.PromotionChannelDOMapperExt;
import com.dy.yunying.biz.dao.manage.ext.WanGameChannelInfoDOMapperExt;
import com.dy.yunying.biz.service.prize.*;
import com.dy.yunying.biz.service.usergroup.UserGroupService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.StringUtil;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.CommonUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 奖励推送表
 *
 * @author chenxiang
 * @version 2022-04-25 16:25:27 table: prize_push
 */
@Slf4j
@Service("prizePushService")
@RequiredArgsConstructor
public class PrizePushServiceImpl extends ServiceImpl<PrizePushMapper, PrizePush> implements PrizePushService {

	private final PrizePushMapper prizePushMapper;

	private final PrizePushGameService prizePushGameService;

	private final PrizePushAreaService prizePushAreaService;

	private final PrizePushChannelService prizePushChannelService;

	private final GameDOMapperExt gameDOMapperExt;

	private final PromotionChannelDOMapperExt promotionChannelDOMapperExt;

	private final WanGameChannelInfoDOMapperExt wanGameChannelInfoDOMapperExt;

	private final ParentGameAreaMapper parentGameAreaMapper;

	private final ParentGameDOMapperExt parentGameDOMapperExt;

	private final PrizePushChannelMapper prizePushChannelMapper;

	private final PrizePushAreaMapper prizePushAreaMapper;

	private final PrizePushGameMapper prizePushGameMapper;

	private final HbSdkDynamicMenusMapper sdkDynamicMenusMapper;

	private final PrizeConfigService prizeConfigService;

	private final PrizeGiftBagService prizeGiftBagService;

	private final UserGroupService userGroupService;

	private final PrizeConfigMapper prizeConfigMapper;

	private final HbActivityMapper hbActivityMapper;

	/**
	 * 分页列表
	 *
	 * @param record
	 * @return
	 */
	@Override
	public R getPage(PrizePushReq record) {
		QueryWrapper<PrizePush> query = getQueryWrapper(record);
		if (StringUtils.isNotBlank(record.getParentGameArr()) || StringUtils.isNotBlank(record.getGameArr())
				|| StringUtils.isNotBlank(record.getAreaArr())) {
			List<Long> noticeIds = baseMapper.selectRangeNoticeId(record.getParentGameArr(), record.getGameArr(),
					record.getAreaArr());
			if (CollectionUtils.isNotEmpty(noticeIds)) {
				query.in("id", noticeIds);
			} else {
				query.eq("id", 0);// 视为匹配不到
			}
		}
		Page<PrizePush> page = new Page<>();
		page.setCurrent(record.getCurrent());
		page.setSize(record.getSize());
		Page<PrizePush> prizePushPage = baseMapper.selectPage(page, query);
		Page<PrizePushRes> resultPage = new Page<PrizePushRes>(page.getCurrent(), page.getSize());
		if (CollectionUtil.isNotEmpty(prizePushPage.getRecords())) {
			resultPage.setTotal(prizePushPage.getTotal());
			resultPage.setCountId(prizePushPage.getCountId());
			resultPage.setPages(prizePushPage.getPages());
			List<PrizePushRes> resultList = new ArrayList<PrizePushRes>();
			List<WanGameDO> gameList = gameDOMapperExt
					.selectList(new QueryWrapper<WanGameDO>().eq("isdelete", Constant.DEL_NO));
			List<NodeParentData> allParentChannelList = promotionChannelDOMapperExt.selectAllChannel();
			List<NodeParentData> allSubChannelList = wanGameChannelInfoDOMapperExt.selectAllSubNodeList();
			List<ParentGameArea> areaList = parentGameAreaMapper.selectList(new QueryWrapper<ParentGameArea>());
			List<NodeData> parentGameList = parentGameDOMapperExt.selectMainGameList();
			List<Long> noticeIdsResult = prizePushPage.getRecords().stream().map(PrizePush::getId)
					.collect(Collectors.toList());
			// 结果集的渠道范围
			List<PrizePushChannel> allActivityChannelList = prizePushChannelMapper
					.selectList(new QueryWrapper<PrizePushChannel>().in("prize_push_id", noticeIdsResult));
			// 结果集的游戏范围
			List<PrizePushGame> allNoticeGameList = prizePushGameMapper
					.selectList(new QueryWrapper<PrizePushGame>().in("prize_push_id", noticeIdsResult));
			// 结果集的区服范围
			List<PrizePushArea> allNoticeAreaList = prizePushAreaMapper
					.selectList(new QueryWrapper<PrizePushArea>().in("prize_push_id", noticeIdsResult));
			//查询配置结果结果集
			List<PrizeConfig> prizeConfigList = prizeConfigMapper.selectPrizeConfigByRangePrizePushId(noticeIdsResult);
			Map<Long, List<PrizeConfig>> listMap = prizeConfigList.stream().collect(Collectors.groupingBy(PrizeConfig::getPrizePushId));
			List<NodeParentData> childChannelList;
			List<NodeParentData> subChannelList;
			List<WanGameDO> childGameList;
			List<ParentGameArea> childAreaList;
			for (PrizePush prizePush : prizePushPage.getRecords()) {
				final PrizePushRes vo = JSON.parseObject(JSON.toJSONString(prizePush), PrizePushRes.class);
				List<PrizePushChannel> activityChannelList = allActivityChannelList.stream()
						.filter(ac -> ac.getPrizePushId().equals(vo.getId())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(activityChannelList)) {
					List<String[]> channelList = new ArrayList<String[]>();
					List<String[]> channelDataList = new ArrayList<String[]>();
					String[] channelArr;
					StringBuffer channelSbStr = new StringBuffer();
					for (PrizePushChannel noticeChannel : activityChannelList) {
						if (1 == noticeChannel.getChannelRange()) {
							childChannelList = allParentChannelList.stream()
									.filter(t -> StringUtils.isNotBlank(t.getPId())
											&& t.getPId().equalsIgnoreCase(noticeChannel.getParentChl()))
									.collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(childChannelList)) {
								for (NodeParentData childChannel : childChannelList) {
									subChannelList = allSubChannelList.stream()
											.filter(t -> StringUtils.isNotBlank(t.getPId())
													&& t.getPId().equalsIgnoreCase(childChannel.getNodeId()))
											.collect(Collectors.toList());
									if (CollectionUtils.isNotEmpty(subChannelList)) {
										for (NodeParentData subChannel : subChannelList) {
											channelArr = new String[]{noticeChannel.getParentChl(),
													childChannel.getNodeId(), subChannel.getNodeId()};
											channelList.add(channelArr);
										}
									} else {
										channelArr = new String[]{noticeChannel.getParentChl(),
												childChannel.getNodeId()};
										channelList.add(channelArr);
									}
								}
							} else {
								channelArr = new String[]{noticeChannel.getParentChl()};
								channelList.add(channelArr);
							}
							String[] channelDataArr = new String[]{noticeChannel.getParentChl()};
							channelDataList.add(channelDataArr);
							channelSbStr
									.append(getChannelNameByCode(noticeChannel.getParentChl(), allParentChannelList))
									.append("(全部)，");
						} else if (2 == noticeChannel.getChannelRange()) {
							subChannelList = allSubChannelList.stream().filter(t -> StringUtils.isNotBlank(t.getPId())
									&& t.getPId().equals(noticeChannel.getChl())).collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(subChannelList)) {
								for (NodeParentData childChannel : subChannelList) {
									channelArr = new String[]{noticeChannel.getParentChl(), noticeChannel.getChl(),
											childChannel.getNodeId()};
									channelList.add(channelArr);
								}
							} else {
								channelArr = new String[]{noticeChannel.getParentChl(), noticeChannel.getChl()};
								channelList.add(channelArr);
							}
							String[] channelDataArr = new String[]{noticeChannel.getParentChl(),
									noticeChannel.getChl()};
							channelDataList.add(channelDataArr);
							channelSbStr
									.append(getChannelNameByCode(noticeChannel.getParentChl(), allParentChannelList))
									.append("-")
									.append(getChannelNameByCode(noticeChannel.getChl(), allParentChannelList))
									.append("(全部)，");
						} else if (3 == noticeChannel.getChannelRange()) {
							channelSbStr
									.append(getChannelNameByCode(noticeChannel.getParentChl(), allParentChannelList))
									.append("-")
									.append(getChannelNameByCode(noticeChannel.getChl(), allParentChannelList))
									.append("-")
									.append(getSubChannelNameByCode(noticeChannel.getAppChl(), allSubChannelList))
									.append("，");
							channelArr = new String[]{noticeChannel.getParentChl(), noticeChannel.getChl(),
									noticeChannel.getAppChl()};
							channelList.add(channelArr);
							String[] channelDataArr = new String[]{noticeChannel.getParentChl(),
									noticeChannel.getChl(), noticeChannel.getAppChl()};
							channelDataList.add(channelDataArr);
						}
					}
					String channelStr = channelSbStr.toString();
					channelStr = channelStr.substring(0, channelStr.length() - 1);
					vo.setChannelNameStr(channelStr);
					vo.setChannelList(channelList);
					vo.setChannelDataList(channelDataList);
				}
				// 游戏范围
				List<PrizePushGame> noticeGameList = allNoticeGameList.stream()
						.filter(ac -> ac.getPrizePushId().equals(vo.getId())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(noticeGameList)) {
					List<Long[]> gameArrList = new ArrayList<Long[]>();
					List<Long[]> gameDataList = new ArrayList<Long[]>();
					Long[] gameArr;
					Long[] gameDataArr;
					StringBuffer gameSbStr = new StringBuffer();
					for (PrizePushGame noticeGame : noticeGameList) {
						if (1 == noticeGame.getGameRange()) {
							childGameList = gameList.stream().filter(
									t -> null != t.getPgid() && t.getPgid().equals(noticeGame.getParentGameId()))
									.collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(childGameList)) {
								for (WanGameDO game : childGameList) {
									gameArr = new Long[]{noticeGame.getParentGameId(), game.getId()};
									gameArrList.add(gameArr);
									gameSbStr.append(getParentGameById(noticeGame.getParentGameId(), parentGameList))
											.append("-").append(getChildGameById(game.getId(), gameList)).append("，");
								}
							} else {
								gameArr = new Long[]{noticeGame.getParentGameId()};
								gameArrList.add(gameArr);
								gameSbStr.append(getParentGameById(noticeGame.getParentGameId(), parentGameList))
										.append("，");
							}
							gameDataArr = new Long[]{noticeGame.getParentGameId()};
							gameDataList.add(gameDataArr);
						} else if (2 == noticeGame.getGameRange()) {
							gameSbStr.append(getParentGameById(noticeGame.getParentGameId(), parentGameList))
									.append("-").append(getChildGameById(noticeGame.getChildGameId(), gameList))
									.append("，");
							gameArr = new Long[]{noticeGame.getParentGameId(), noticeGame.getChildGameId()};
							gameArrList.add(gameArr);
							gameDataArr = new Long[]{noticeGame.getParentGameId(), noticeGame.getChildGameId()};
							gameDataList.add(gameDataArr);
						}
					}
					String gameStr = gameSbStr.toString();
					gameStr = gameStr.substring(0, gameStr.length() - 1);
					vo.setGameNameStr(gameStr);
					vo.setGameList(gameArrList);
					vo.setGameDataList(gameDataList);
				}
				// 游戏区服
				List<PrizePushArea> noticeAreaList = allNoticeAreaList.stream()
						.filter(ac -> ac.getPrizePushId().equals(vo.getId())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(noticeAreaList)) {
					List<Long[]> areaArrList = new ArrayList<Long[]>();
					List<Long[]> areaDataList = new ArrayList<Long[]>();
					Long[] areaArr;
					Long[] areaDataArr;
					StringBuffer areaSbStr = new StringBuffer();
					for (PrizePushArea noticeArea : noticeAreaList) {
						if (1 == noticeArea.getAreaRange()) {
							childAreaList = areaList.stream()
									.filter(t -> null != t.getParentGameId()
											&& t.getParentGameId().equals(noticeArea.getParentGameId()))
									.collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(childAreaList)) {
								for (ParentGameArea area : childAreaList) {
									areaArr = new Long[]{noticeArea.getParentGameId(), area.getAreaId()};
									areaArrList.add(areaArr);
									areaSbStr.append(getParentGameById(noticeArea.getParentGameId(), parentGameList))
											.append("-").append(getAreaById(noticeArea.getParentGameId(),
											area.getAreaId(), areaList))
											.append("，");
								}
							} else {
								areaArr = new Long[]{noticeArea.getParentGameId()};
								areaArrList.add(areaArr);
								areaSbStr.append(getParentGameById(noticeArea.getParentGameId(), parentGameList))
										.append("，");
							}
							areaDataArr = new Long[]{noticeArea.getParentGameId()};
							areaDataList.add(areaDataArr);
						} else if (2 == noticeArea.getAreaRange()) {
							areaSbStr.append(getParentGameById(noticeArea.getParentGameId(), parentGameList))
									.append("-")
									.append(getAreaById(noticeArea.getParentGameId(), noticeArea.getAreaId(), areaList))
									.append("，");
							areaArr = new Long[]{noticeArea.getParentGameId(), noticeArea.getAreaId()};
							areaArrList.add(areaArr);
							areaDataArr = new Long[]{noticeArea.getParentGameId(), noticeArea.getAreaId()};
							areaDataList.add(areaDataArr);
						}
					}
					String areaStr = areaSbStr.toString();
					areaStr = areaStr.substring(0, areaStr.length() - 1);
					vo.setAreaNameStr(areaStr);
					vo.setAreaList(areaArrList);
					vo.setAreaDataList(areaDataList);
				}
				//奖励配置内容
				//奖励配置
				List<PrizeConfig> prizeConfigs = listMap.get(prizePush.getId());
				if (CollectionUtils.isNotEmpty(prizeConfigs)) {
					List<String> prizeTitles = new ArrayList<>();
					List<PrizeConfigRes> list = new ArrayList<>();
					//TODO
					prizeConfigs.forEach(new Consumer<PrizeConfig>() {
						@Override
						public void accept(PrizeConfig prizeConfig) {
							PrizeConfigRes prizeConfigRes = new PrizeConfigRes();
							BeanUtils.copyProperties(prizeConfig,prizeConfigRes);
							list.add(prizeConfigRes);
							if (PrizeTypeEnum.VOUCHER.getType().equals(prizeConfig.getPrizeType())) {
								prizeTitles.add(prizeConfig.getMoney() + "元代金券，满"+prizeConfig.getLimitMoney() + "可用");
							} else if (PrizeTypeEnum.SWIMBEAN.getType().equals(prizeConfig.getPrizeType())) {
								if (prizeConfig.getCurrencyType()==1){
									prizeTitles.add(prizeConfig.getMoney() + "常规游豆");
								} else {
									prizeTitles.add(prizeConfig.getMoney() + "临时游豆");
								}

							}else {
								PrizeTypeEnum prizeTypeEnum = PrizeTypeEnum.getPrizeTypeEnum(prizeConfig.getPrizeType());
								if (prizeTypeEnum != null){
									prizeTitles.add(prizeTypeEnum.getName());
								}
							}
						}
					});
					vo.setPrizeConfigList(list);
					vo.setPrizeTitles(String.join("、",prizeTitles));
				}
				//群组名称集合
				String userGroupId = prizePush.getUserGroupId();
				if (StringUtils.isNotBlank(userGroupId)){
					String[] useGroup = userGroupId.split(",");
					List<String> useGroupList = Arrays.asList(useGroup);
					List<UserGroup> list = userGroupService.list(Wrappers.<UserGroup>lambdaQuery().in(UserGroup::getId, useGroupList));
					if (CollectionUtils.isNotEmpty(list)){
						List<String> useGroupNameList = list.stream().map(userGroup -> userGroup.getGroupName()).collect(Collectors.toList());
						vo.setUserGroupNameStr(String.join(",",useGroupNameList));
					}
				}

				//列表转跳展示  pushSkipTypeStr
				PushPrizeTypeEnum pushPrizeTypeEnum = PushPrizeTypeEnum.getPushPrizeTypeEnum(prizePush.getPushPrizeType());
				if (pushPrizeTypeEnum == PushPrizeTypeEnum.SINGLE){
					if (CollectionUtils.isNotEmpty(prizeConfigs)){
						PrizeConfig prizeConfig = prizeConfigs.get(0);
						PrizeTypeEnum prizeTypeEnum = PrizeTypeEnum.getPrizeTypeEnum(prizeConfig.getPrizeType());
						switch (prizeTypeEnum){
							case BAGCODE:
							case CAMILO:
								vo.setPushSkipTypeStr("-");
								break;
							case VOUCHER:
							case SWIMBEAN:
								setPushSkipType(vo, prizeConfig.getOpenType(), prizeConfig.getMenuTitle(), prizeConfig.getSkipUrl(), prizeConfig.getSkipId());
								break;
						}
					}
				}
				if (pushPrizeTypeEnum == PushPrizeTypeEnum.MUTI){
					if (!PopupMoldEnum.MSG.getType().equals(prizePush.getPopupMold())){
						setPushSkipType(vo, prizePush.getOpenType(), prizePush.getMenuTitle(), prizePush.getSkipUrl(), prizePush.getSkipId());
					} else {
						vo.setPushSkipTypeStr("-");
					}
				}
				resultList.add(vo);
			}
			resultPage.setRecords(resultList);
		}

		return R.ok(resultPage);
	}


	private void setPushSkipType(PrizePushRes vo, Integer openType, String menuTitle, String skipUrl, Long skipId) {
		PrizeOpenTypeEnum prizeOpenTypeEnum = PrizeOpenTypeEnum.getPrizeOpenTypeEnum(openType);
		switch (prizeOpenTypeEnum) {
			case SDK:
				String[] splitTitles = menuTitle.split(",");
				List<String> list = Arrays.asList(splitTitles);
				String activityName = "";
				if (skipId != null && menuTitle.startsWith("活动")){
					HbActivity hbActivity = hbActivityMapper.selectById(skipId);
					if (hbActivity != null){
						activityName = hbActivity.getActivityName();
					}
				}
				if (1 == vo.getSkipMold().intValue() && StringUtils.isNotBlank(activityName)){
					vo.setPushSkipTypeStr(String.join("-",list)+"-"+activityName);
				} else{
					vo.setPushSkipTypeStr(String.join("-",list));
				}
				break;
			case URL:
			case BROWER:
				vo.setPushSkipTypeStr(skipUrl);
				break;
			case NOJUMP:
			default:
				vo.setPushSkipTypeStr("-");
				break;
		}
	}

	private String getAreaById(Long parentGameId, Long areaId, List<ParentGameArea> areaList) {
		if (CollectionUtils.isNotEmpty(areaList)) {
			for (ParentGameArea area : areaList) {
				if (parentGameId.equals(area.getParentGameId()) && areaId.equals(area.getAreaId())) {
					return area.getAreaName();
				}
			}
		}
		return "";
	}

	private String getChildGameById(Long id, List<WanGameDO> gameList) {
		if (CollectionUtils.isNotEmpty(gameList)) {
			for (WanGameDO game : gameList) {
				if (id.equals(game.getId())) {
					return game.getGname();
				}
			}
		}
		return "";
	}

	private String getParentGameById(Long id, List<NodeData> parentGameList) {
		if (CollectionUtils.isNotEmpty(parentGameList)) {
			for (NodeData node : parentGameList) {
				if (id.toString().equals(node.getNodeId())) {
					return node.getNodeName();
				}
			}
		}
		return "";
	}

	private String getChannelNameByCode(String code, List<NodeParentData> parentCahnnelList) {
		if (CollectionUtils.isNotEmpty(parentCahnnelList)) {
			for (NodeParentData node : parentCahnnelList) {
				if (code.equalsIgnoreCase(node.getNodeId())) {
					return node.getNodeName();
				}
			}
		}
		return "";
	}

	private String getSubChannelNameByCode(String code, List<NodeParentData> subCahnnelList) {
		if (CollectionUtils.isNotEmpty(subCahnnelList)) {
			for (NodeParentData node : subCahnnelList) {
				if (code.equalsIgnoreCase(node.getNodeId())) {
					return node.getNodeName();
				}
			}
		}
		return "";
	}

	private QueryWrapper<PrizePush> getQueryWrapper(PrizePushReq record) {
		QueryWrapper<PrizePush> query = new QueryWrapper<PrizePush>();
		if (StringUtils.isNotBlank(record.getStartTime())) {
			query.ge("DATE_FORMAT(start_time,'%Y%m%d')", record.getStartTime());
		}
		if (StringUtils.isNotBlank(record.getEndTime())) {
			query.le("DATE_FORMAT(start_time,'%Y%m%d')", record.getEndTime());
		}
		if (StringUtils.isNotBlank(record.getPopupMold())) {
			query.eq("popup_mold", record.getPopupMold());
		}
		if (StringUtils.isNotBlank(record.getPushNode())) {
			query.eq("push_node", record.getPushNode());
		}
		if (StringUtils.isNotBlank(record.getPushType())) {
			query.eq("push_type", record.getPushType());
		}
		if (StringUtils.isNotBlank(record.getStatus())) {
			Integer status = Integer.valueOf(record.getStatus());
			if (PrizePushStatusEnum.READY.getType().equals(status)) {
				query.eq("status", PrizePushStatusEnum.START.getType());
				query.ge("DATE_FORMAT(start_time,'%Y-%m-%d %H:%i:%S')", DateUtils.getcurrentTime());
			} else if (PrizePushStatusEnum.ACTIVITING.getType().equals(status)) {
				query.eq("status", PrizePushStatusEnum.START.getType());
				query.le("DATE_FORMAT(start_time,'%Y-%m-%d %H:%i:%S')", DateUtils.getcurrentTime());
				query.ge("DATE_FORMAT(end_time,'%Y-%m-%d %H:%i:%S')", DateUtils.getcurrentTime());
			} else if (PrizePushStatusEnum.CLOSE.getType().equals(status)) {
				query.eq("status", PrizePushStatusEnum.START.getType());
				query.le("DATE_FORMAT(end_time,'%Y-%m-%d %H:%i:%S')", DateUtils.getcurrentTime());
			} else if (PrizePushStatusEnum.START.getType().equals(status)) {
				query.eq("status", PrizePushStatusEnum.START.getType());
			} else if (PrizePushStatusEnum.STOP.getType().equals(status)) {
				query.eq("status", PrizePushStatusEnum.STOP.getType());
			}
		}
		query.eq("deleted", Constant.DEL_NO);
		if (StringUtils.isNotBlank(record.getSortType())) {
			if (Constant.ORDER_DESC.equalsIgnoreCase(record.getSortType())) {
				query.orderByDesc("show_sort");
			} else if (Constant.ORDER_ASC.equalsIgnoreCase(record.getSortType())) {
				query.orderByAsc("show_sort");
			}
		} else {
			query.orderByDesc("id");
		}
		return query;
	}

	/**
	 * 新增-编辑
	 *
	 * @param record
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public R createEdit(PrizePushReq record) {
		String message = "";
		String menuTitle = record.getMenuTitle();

		if (StringUtil.isNotBlank(record.getOpenType())) {
			PrizeOpenTypeEnum prizeOpenTypeEnum = PrizeOpenTypeEnum.getPrizeOpenTypeEnum(Integer.valueOf(record.getOpenType()));
			if (prizeOpenTypeEnum == PrizeOpenTypeEnum.SDK) {
				if (StringUtils.isNotBlank(menuTitle)) {
					R result = this.setMenuInfoToPrizePush(record, menuTitle);
					if (CommonConstants.FAIL.equals(result.getCode())) {
						return R.failed("无法获取SDK菜单数据");
					}
				}
			} else {
				record.setSkipUrlIOS(record.getSkipUrl());
			}
		}

		PrizePush prizePush = new PrizePush();
		// 奖品推送对象
		prizePushBean(prizePush, record);
		if (StringUtils.isBlank(record.getId())) {
			prizePush.setCreateTime(new Date());
			prizePush.setCreateId(SecurityUtils.getUser().getId().longValue());
			// 新增
			this.save(prizePush);
			record.setId(String.valueOf(prizePush.getId()));
			message = "新增奖励推送成功";
		} else {
			prizePush.setUpdateTime(new Date());
			prizePush.setUpdateId(SecurityUtils.getUser().getId().longValue());
			// 查询之前的推送类型，如果之前奖励推送类型和现在的不一致，奖励删除之前奖励配置
			// 编辑之前的可以获取现在的id，将之前的id删除
			List<PrizeConfigReq> prizeConfigList = record.getPrizeConfigList();
			List<Long> prizeConfigIds = prizeConfigList.stream().filter(configReq -> {
				if (StringUtil.isNotBlank(configReq.getId())){
					return true;
				}
				return false;
			}).map(configReq -> Long.valueOf(configReq.getId())).collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(prizeConfigIds)){
				prizeConfigService.remove(Wrappers.<PrizeConfig>lambdaQuery().eq(PrizeConfig::getPrizePushId,prizePush.getId()).notIn(PrizeConfig::getId,prizeConfigIds));
			}
			// 编辑
			this.updateById(prizePush);
			message = "编辑奖励推送成功";
		}

		// 奖品推送 游戏，区服，渠道关系
		prizeGameAreaChannel(record);
		List<PrizeConfigReq> prizeConfigList = record.getPrizeConfigList();
		//TODO 如果是单个奖励（只取最新的那个吗其余的删除？）
//		if (PushPrizeTypeEnum.SINGLE.getType().equals(Integer.valueOf(record.getPushPrizeType()))) {
//			PrizeConfigReq prizeConfigReq = prizeConfigList.get(0);
//			if (prizePush.getId() != null){
//				prizeConfigReq.setPrizePushId(String.valueOf(prizePush.getId()));
//			}
//			prizeConfigService.savePrizeConfig(prizeConfigReq);
//		} else {
			// 组合奖励，更新配置里面奖励推送id
			List<PrizeConfig> prizeConfigs = new ArrayList<>();
			for (PrizeConfigReq prizeConfigReq : prizeConfigList) {
				if (StringUtils.isBlank(prizeConfigReq.getId())) {
					return R.failed("奖励配置主键Id不能为空");
				}
				PrizeConfig prizeConfig = new PrizeConfig();
				prizeConfig.setId(Long.valueOf(prizeConfigReq.getId()));
				prizeConfig.setPrizePushId(prizePush.getId());
				prizeConfigs.add(prizeConfig);
			}
			log.info("批量更新奖励配置的推送id, prizeConfigs = {}", JSON.toJSONString(prizeConfigs));
			prizeConfigService.updateBatchById(prizeConfigs);
//		}

		return R.ok(0,message);
	}

	private R setMenuInfoToPrizePush(PrizePushReq record, String menuTitle) {
		String[] menuTitles = menuTitle.split(",");
		StringBuilder skipUrl = new StringBuilder();
		StringBuilder skipUrlIOS = new StringBuilder();
		String resourceLink = "";
		String resourceLinkIOS = "";
		if (StringUtil.isNotBlank(record.getSkipId())){
			Integer skipId = Integer.valueOf(record.getSkipId());
			HbActivity hbActivity = hbActivityMapper.selectById(skipId);
			if (hbActivity != null){
				record.setSkipBelongType(hbActivity.getActivityType()+"");
			}
		}
		if (menuTitles.length > 0) {
			String firstMenuTitle = menuTitles[0];
			List<HbSdkDynamicMenus> sdkDynamicMenusList = sdkDynamicMenusMapper.selectList(
					Wrappers.<HbSdkDynamicMenus>lambdaQuery().eq(HbSdkDynamicMenus::getMenuTitle, firstMenuTitle)
							.eq(HbSdkDynamicMenus::getStatus, 1).eq(HbSdkDynamicMenus::getDeleted, 0));
			if (CollectionUtils.isNotEmpty(sdkDynamicMenusList)) {
				for (HbSdkDynamicMenus sdkDynamicMenus : sdkDynamicMenusList) {
					if (2 == sdkDynamicMenus.getOsType()) {
						resourceLink = StringUtil.isNotBlank(sdkDynamicMenus.getResourceLink()) ? sdkDynamicMenus.getResourceLink() : "";
						if (Objects.nonNull(record.getSkipMold())) {
							if ("1".equals(record.getSkipMold())) {
								resourceLink = resourceLink.replace("#/activity", "#/redBag");
							} else if ("2".equals(record.getSkipMold())) {
								resourceLink = resourceLink.replace("#/activity", "#/signIn");
							}
						}
						record.setMenuCode(sdkDynamicMenus.getMenuCode());
						skipUrl.append("?")
								.append("menuCode")
								.append("=").append(sdkDynamicMenus.getMenuCode());
					} else if (3 == sdkDynamicMenus.getOsType()) {
						resourceLinkIOS = StringUtil.isNotBlank(sdkDynamicMenus.getResourceLink()) ? sdkDynamicMenus.getResourceLink() : "";
						if (Objects.nonNull(record.getSkipMold())) {
							if ("1".equals(record.getSkipMold())) {
								resourceLinkIOS = resourceLinkIOS.replace("/activity?", "/redBag?");
							} else if ("2".equals(record.getSkipMold())) {
								resourceLinkIOS = resourceLinkIOS.replace("/activity?", "/signIn?");
							}
						}
						record.setMenuCodeIos(sdkDynamicMenus.getMenuCode());
						skipUrlIOS.append("?")
								.append("menuCodeIos")
								.append("=").append(sdkDynamicMenus.getMenuCode());
					}
				}
			} else {
				return R.failed("无法获取SDK菜单数据");
			}
		}
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("&sourceBelongType=").append(convertString(record.getSkipBelongType()))
				.append("&sourceId=").append(convertString(record.getSkipId()))
				.append("&activityId=").append(convertString(record.getSkipId()))
				.append("&sourceMold=").append(convertString(record.getSkipMold()));
		skipUrl.append(stringBuilder);
		skipUrlIOS.append(stringBuilder);
		record.setSkipUrl(resourceLink+skipUrl.toString());
		record.setSkipUrlIOS(resourceLinkIOS+skipUrlIOS.toString());
		return R.ok();
	}

	private String convertString(String str) {
		if (StringUtil.isNotBlank(str)){
			if (!"0".equals(str)){
				return str;
			}
		}
		return "";
	}

	@Override
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public R prizePushStartOrStop(PrizeOnlineOrOfflineReq req) {
		String message = "";
		PrizePush info;
		if (PrizePushStatusEnum.START.getType().equals(req.getStatus())) {
			info = baseMapper.selectOne(new QueryWrapper<PrizePush>().eq("id", req.getId()).ne("status",
					PrizePushStatusEnum.START.getType()));
			if (null == info) {
				return R.failed("当前状态无法启用");
			}
			if (info.getEndTime().getTime() < System.currentTimeMillis()) {
				return R.failed("结束时间不能比当前时间小");
			}
			message = "奖励推送启动成功";
		} else if (PrizePushStatusEnum.STOP.getType().equals(req.getStatus())) {
			info = baseMapper.selectOne(new QueryWrapper<PrizePush>().eq("id", req.getId()).eq("status",
					PrizePushStatusEnum.START.getType()));
			if (null == info) {
				return R.failed("当前状态无法停用");
			}
			message = "奖励推送停用成功";
		} else {
			//
			return R.failed("操作参数不合法");
		}
		info.setStatus(req.getStatus());
		info.setUpdateTime(new Date());
		info.setUpdateId(SecurityUtils.getUser().getId().longValue());
		baseMapper.updateById(info);
		return R.ok(0,message);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public R doRemoveById(Long id) {
		PrizePush prizePush = new PrizePush();
		prizePush.setId(id);
		prizePush.setUpdateId(SecurityUtils.getUser().getId().longValue());
		prizePush.setUpdateTime(new Date());
		// 删除
		prizePushMapper.update(prizePush,
				Wrappers.<PrizePush>lambdaUpdate().eq(PrizePush::getId, id).set(PrizePush::getDeleted, 1));
		// 2、再删推送关联的游戏渠道区服
		deleteGameChannelArea(id);
		// 3、奖励配置、
		// 查询奖励配置根据推送id
		List<PrizeConfig> prizeConfigs = prizeConfigService.list(
				Wrappers.<PrizeConfig>lambdaQuery().eq(PrizeConfig::getPrizePushId, id).eq(PrizeConfig::getDeleted, 0));
		prizeConfigService.remove(
				Wrappers.<PrizeConfig>lambdaQuery().eq(PrizeConfig::getPrizePushId, id).eq(PrizeConfig::getDeleted, 0));
		if (CollectionUtils.isNotEmpty(prizeConfigs)) {
			prizeConfigs.forEach(new Consumer<PrizeConfig>() {
				@Override
				public void accept(PrizeConfig prizeConfig) {
					if (GiftTypeEnum.UNIQUE.getType().equals(prizeConfig.getGiftType())) {
						prizeGiftBagService.remove(Wrappers.<PrizeGiftBag>lambdaQuery()
								.eq(PrizeGiftBag::getSourceId, prizeConfig.getId()).eq(PrizeGiftBag::getDeleted, 0));
					}

				}
			});
		}
		return R.ok(0,"奖励推送删除成功");
	}

	@Override
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public R copy(Long id) {
		PrizePush prizePush = prizePushMapper.selectById(id);
		if (prizePush == null){
			return R.failed("奖励推送主键id不存在");
		}
		//复制奖励推送

		prizePush.setId(null);
		prizePush.setStatus(PrizePushStatusEnum.STOP.getType());
		prizePush.setCreateId(SecurityUtils.getUser().getId().longValue());
		prizePush.setCreateTime(new Date());
		//
		prizePushMapper.insert(prizePush);

		//复制奖励配置
		List<PrizeConfig> prizeConfigList = prizeConfigService.list(Wrappers.<PrizeConfig>lambdaQuery().eq(PrizeConfig::getPrizePushId, id));
		if (CollectionUtils.isNotEmpty(prizeConfigList)){

			List<PrizeConfig> collect = prizeConfigList.stream().map(new Function<PrizeConfig, PrizeConfig>() {
				@Override
				public PrizeConfig apply(PrizeConfig prizeConfig) {
					prizeConfig.setPrizePushId(prizePush.getId());
					prizeConfig.setId(null);
					prizeConfig.setCreateId(SecurityUtils.getUser().getId().longValue());
					prizeConfig.setCreateTime(new Date());
					prizeConfig.setGiftCode(null);
					prizeConfig.setGiftAmount(null);
					return prizeConfig;
				}
			}).collect(Collectors.toList());
			prizeConfigService.saveOrUpdateBatch(collect);
		}

		//新的奖励配置id
//		List<PrizeConfig> newPrizeConfigs = prizeConfigService.list(Wrappers.<PrizeConfig>lambdaQuery().eq(PrizeConfig::getPrizePushId, prizePush.getId()));
//		if (CollectionUtils.isNotEmpty(newPrizeConfigs)){
//			List<PrizeConfig> collect = newPrizeConfigs.stream().filter(new Predicate<PrizeConfig>() {
//				@Override
//				public boolean test(PrizeConfig prizeConfig) {
//					GiftTypeEnum giftTypeEnum = GiftTypeEnum.getGiftTypeEnum(prizeConfig.getGiftType());
//					PrizeTypeEnum prizeTypeEnum = PrizeTypeEnum.getPrizeTypeEnum(prizeConfig.getPrizeType());
//					//唯一码是全局唯一的
//					if (giftTypeEnum == GiftTypeEnum.COMMON && (prizeTypeEnum == PrizeTypeEnum.BAGCODE || prizeTypeEnum == PrizeTypeEnum.CAMILO)) {
//						return true;
//					}
//					return false;
//				}
//			}).collect(Collectors.toList());
//			if (CollectionUtils.isNotEmpty(collect)){
//				List<PrizeGiftBag> prizeGiftBagList = collect.stream().map(new Function<PrizeConfig, PrizeGiftBag>() {
//					@Override
//					public PrizeGiftBag apply(PrizeConfig prizeConfig) {
//						PrizeGiftBag giftBag = new PrizeGiftBag();
//						giftBag.setSourceType(prizeConfig.getPrizeType());
//						giftBag.setSourceId(prizeConfig.getId());
//						giftBag.setGiftCode(prizeConfig.getGiftCode());
//						giftBag.setGiftAmount(Long.valueOf(prizeConfig.getGiftAmount()));
//						giftBag.setUsable(prizeConfig.getGiftType());
//						giftBag.setCreateTime(new Date());
//						giftBag.setUpdateTime(new Date());
//						giftBag.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
//						return giftBag;
//					}
//				}).collect(Collectors.toList());
//				prizeGiftBagService.saveOrUpdateBatch(prizeGiftBagList);
//			}
//		}

		//复制游戏渠道区服
		List<PrizePushGame> prizePushGames = prizePushGameMapper.selectList(Wrappers.<PrizePushGame>lambdaQuery().eq(PrizePushGame::getPrizePushId, id));
		if (CollectionUtils.isNotEmpty(prizePushGames)){
			List<PrizePushGame> collect = prizePushGames.stream().map(new Function<PrizePushGame, PrizePushGame>() {

				@Override
				public PrizePushGame apply(PrizePushGame prizePushGame) {
					prizePushGame.setPrizePushId(prizePush.getId());
					prizePushGame.setId(null);
					prizePushGame.setCreateId(SecurityUtils.getUser().getId().longValue());
					prizePushGame.setCreateTime(new Date());
					prizePushGame.setUpdateId(SecurityUtils.getUser().getId().longValue());
					prizePushGame.setUpdateTime(new Date());
					return prizePushGame;
				}
			}).collect(Collectors.toList());
			prizePushGameService.saveOrUpdateBatch(collect);
		}

		List<PrizePushChannel> prizePushChannels = prizePushChannelService.list(Wrappers.<PrizePushChannel>lambdaQuery().eq(PrizePushChannel::getPrizePushId, id));
		if (CollectionUtils.isNotEmpty(prizePushChannels)){
			List<PrizePushChannel> collect = prizePushChannels.stream().map(new Function<PrizePushChannel, PrizePushChannel>() {

				@Override
				public PrizePushChannel apply(PrizePushChannel prizePushChannel) {
					prizePushChannel.setPrizePushId(prizePush.getId());
					prizePushChannel.setId(null);
					prizePushChannel.setCreateId(SecurityUtils.getUser().getId().longValue());
					prizePushChannel.setCreateTime(new Date());
					prizePushChannel.setUpdateId(SecurityUtils.getUser().getId().longValue());
					prizePushChannel.setUpdateTime(new Date());
					return prizePushChannel;
				}
			}).collect(Collectors.toList());
			prizePushChannelService.saveOrUpdateBatch(collect);
		}

		List<PrizePushArea> prizePushAreas = prizePushAreaService.list(Wrappers.<PrizePushArea>lambdaQuery().eq(PrizePushArea::getPrizePushId, id));

		if (CollectionUtils.isNotEmpty(prizePushAreas)){
			List<PrizePushArea> collect = prizePushAreas.stream().map(new Function<PrizePushArea, PrizePushArea>() {
				@Override
				public PrizePushArea apply(PrizePushArea prizePushArea) {
					prizePushArea.setPrizePushId(prizePush.getId());
					prizePushArea.setId(null);
					prizePushArea.setCreateId(SecurityUtils.getUser().getId().longValue());
					prizePushArea.setCreateTime(new Date());
					prizePushArea.setUpdateId(SecurityUtils.getUser().getId().longValue());
					prizePushArea.setUpdateTime(new Date());
					return prizePushArea;
				}
			}).collect(Collectors.toList());
			prizePushAreaService.saveOrUpdateBatch(collect);
		}


		return R.ok();
	}

	private void deleteGameChannelArea(Long id) {
		PrizePushGame prizePushGame = new PrizePushGame();
		prizePushGame.setPrizePushId(id);
		prizePushGame.setUpdateId(SecurityUtils.getUser().getId().longValue());
		prizePushGame.setUpdateTime(new Date());
		prizePushGameMapper.update(prizePushGame, Wrappers.<PrizePushGame>lambdaUpdate()
				.eq(PrizePushGame::getPrizePushId, id).set(PrizePushGame::getDeleted, 1));

		PrizePushChannel prizePushChannel = new PrizePushChannel();
		prizePushChannel.setPrizePushId(id);
		prizePushChannel.setUpdateId(SecurityUtils.getUser().getId().longValue());
		prizePushChannel.setUpdateTime(new Date());
		prizePushChannelMapper.update(prizePushChannel, Wrappers.<PrizePushChannel>lambdaUpdate()
				.eq(PrizePushChannel::getPrizePushId, id).set(PrizePushChannel::getDeleted, 1));

		PrizePushArea prizePushArea = new PrizePushArea();
		prizePushArea.setPrizePushId(id);
		prizePushArea.setUpdateId(SecurityUtils.getUser().getId().longValue());
		prizePushArea.setUpdateTime(new Date());
		prizePushAreaMapper.update(prizePushArea, Wrappers.<PrizePushArea>lambdaUpdate()
				.eq(PrizePushArea::getPrizePushId, id).set(PrizePushArea::getDeleted, 1));

	}

	/**
	 * 奖品推送 游戏，区服，渠道关系
	 *
	 * @param record
	 */
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public void prizeGameAreaChannel(PrizePushReq record) {
		Long prizePushId = Long.valueOf(record.getId());
		if (Objects.isNull(prizePushId)) {
			throw new NullPointerException("奖品推送为空");
		}
		if (CollectionUtils.isNotEmpty(record.getChannelList())) {
			// 更新渠道关系
			List<PrizePushChannel> insertList = Lists.newArrayList();
			PrizePushChannel channel;
			for (String[] channelArr : record.getChannelList()) {
				if (channelArr.length > 0) {
					channel = new PrizePushChannel();
					channel.setPrizePushId(prizePushId);
					if (1 == channelArr.length) {
						channel.setParentChl(channelArr[0]);
						channel.setChannelRange(1);
					}
					if (2 == channelArr.length) {
						channel.setParentChl(channelArr[0]);
						channel.setChl(channelArr[1]);
						channel.setChannelRange(2);
					}
					if (3 == channelArr.length) {
						channel.setParentChl(channelArr[0]);
						channel.setChl(channelArr[1]);
						channel.setAppChl(channelArr[2]);
						channel.setChannelRange(3);
					}
					channel.setCreateTime(new Date());
					insertList.add(channel);
				}
			}
			if (CollectionUtils.isNotEmpty(insertList)) {
				// 删除关系
				prizePushChannelService.remove(
						Wrappers.<PrizePushChannel>lambdaQuery().eq(PrizePushChannel::getPrizePushId, prizePushId));
				// 批量新增
				prizePushChannelService.saveBatch(insertList);
			}
		}
		if (CollectionUtils.isNotEmpty(record.getGameList())) {
			// 更新游戏关系
			List<PrizePushGame> insertList = Lists.newArrayList();
			PrizePushGame game;
			for (String[] gameArr : record.getGameList()) {
				if (gameArr.length > 0) {
					game = new PrizePushGame();
					game.setPrizePushId(prizePushId);
					if (1 == gameArr.length) {
						game.setParentGameId(Long.valueOf(gameArr[0]));
						game.setGameRange(1);
					}
					if (2 == gameArr.length) {
						game.setParentGameId(Long.valueOf(gameArr[0]));
						game.setChildGameId(Long.valueOf(gameArr[1]));
						game.setGameRange(2);
					}
					game.setCreateTime(new Date());
					insertList.add(game);
				}
			}
			if (CollectionUtils.isNotEmpty(insertList)) {
				// 删除关系
				prizePushGameService
						.remove(Wrappers.<PrizePushGame>lambdaQuery().eq(PrizePushGame::getPrizePushId, prizePushId));
				// 批量新增
				prizePushGameService.saveBatch(insertList);
			}
		}
		if (CollectionUtils.isNotEmpty(record.getAreaList())) {
			// 更新区服关系
			List<PrizePushArea> insertList = Lists.newArrayList();
			PrizePushArea area;
			for (String[] areaArr : record.getAreaList()) {
				area = new PrizePushArea();
				area.setPrizePushId(prizePushId);
				if (1 == areaArr.length) {
					area.setParentGameId(Long.valueOf(areaArr[0]));
					area.setAreaRange(1);
				}
				if (2 == areaArr.length) {
					area.setParentGameId(Long.valueOf(areaArr[0]));
					area.setAreaId(Long.valueOf(areaArr[1]));
					area.setAreaRange(2);
				}
				area.setCreateTime(new Date());
				insertList.add(area);
			}
			if (CollectionUtils.isNotEmpty(insertList)) {
				// 删除关系
				prizePushAreaService
						.remove(Wrappers.<PrizePushArea>lambdaQuery().eq(PrizePushArea::getPrizePushId, prizePushId));
				// 批量新增
				prizePushAreaService.saveBatch(insertList);
			}
		}
	}

	/**
	 * 奖品推送对象
	 *
	 * @param prizePush
	 * @param record
	 */
	public void prizePushBean(PrizePush prizePush, PrizePushReq record) {
		prizePush.setId(StringUtil.isNotBlank(record.getId()) ? Long.valueOf(record.getId()) : 0);
		prizePush.setUserGroupId(record.getUserGroupId());
		prizePush.setTitle(record.getTitle());
		prizePush.setDescription(record.getDescription());
		prizePush.setIcon(record.getIcon());
		prizePush.setPushPrizeType(StringUtil.isNotBlank(record.getPushPrizeType()) ? Integer.valueOf(record.getPushPrizeType()) : 1);
		prizePush.setPushTarget(record.getPushTarget());
		prizePush.setStartTime(DateUtils.stringToDate(record.getStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		prizePush.setEndTime(DateUtils.stringToDate(record.getEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		prizePush.setPushType(Integer.valueOf(record.getPushType()));
		prizePush.setPushInterval(record.getPushInterval());
		prizePush.setPushNode(StringUtil.isNotBlank(record.getPushNode()) ? Integer.valueOf(record.getPushNode()) : 0);
		if (StringUtil.isNotBlank(record.getPushPrizeType())){
			//如果是单个弹窗，弹窗类型修改成单个类型
			if (PushPrizeTypeEnum.SINGLE.getType().equals(Integer.valueOf(record.getPushPrizeType()))){
				prizePush.setPopupMold(PushPrizeTypeEnum.SINGLE.getType());
			}else {
				prizePush.setPopupMold(StringUtil.isNotBlank(record.getPopupMold()) ? Integer.valueOf(record.getPopupMold()) : 1);
			}
		}
		prizePush.setOpenType(StringUtil.isNotBlank(record.getOpenType()) ? Integer.valueOf(record.getOpenType()) : 0);
		if (StringUtil.isBlank(record.getMenuTitle())){
			prizePush.setMenuId("");
		} else {
			prizePush.setMenuId(record.getMenuId());
		}
		prizePush.setMenuTitle(record.getMenuTitle());
		prizePush.setMenuCode(record.getMenuCode());
		prizePush.setMenuCodeIos(record.getMenuCodeIos());
		prizePush.setSecondMenuCode(record.getSecondMenuCode());
		prizePush.setSecondMenuCodeIos(record.getSecondMenuCodeIos());
		prizePush.setSkipUrl(record.getSkipUrl());
		prizePush.setSkipUrlIOS(record.getSkipUrlIOS());
		prizePush.setSkipMold(StringUtil.isNotBlank(record.getSkipMold()) ? Integer.valueOf(record.getSkipMold()) : 0);
		prizePush.setSkipBelongType(
				StringUtil.isNotBlank(record.getSkipBelongType()) ? Integer.valueOf(record.getSkipBelongType()) : 0);
		prizePush.setSkipId(StringUtil.isNotBlank(record.getSkipId()) ? Long.valueOf(record.getSkipId()) : null);
		prizePush.setShowSort(StringUtil.isNotBlank(record.getShowSort()) ? Integer.valueOf(record.getShowSort()) : 1);
		prizePush.setShowType(StringUtil.isNotBlank(record.getShowType()) ? Integer.valueOf(record.getShowType()) : 1);
	}

	@Override
	public List<UserGroupStatVO> countWithUserGroupIds(List<Long> userGroupIds) {
		return prizePushMapper.countWithUserGroupIds(userGroupIds);
	}

	@Override
	public List<Long> getPrizeIdsWithUserGroupId(Long userGroupId) {
		return prizePushMapper.getPrizeIdsWithUserGroupId(userGroupId);
	}
}
